package com.example.classconnect;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.classconnect.fragments.AddNewClassFragment;
import com.example.classconnect.fragments.Fragment7;
import com.example.classconnect.fragments.FriendsFragment;
import com.example.classconnect.fragments.HomeFragment;
import com.example.classconnect.fragments.MapFragment;
import com.example.classconnect.fragments.ProfileFragment;
import com.example.classconnect.fragments.UpdateUserInfoFragment;
import com.example.classconnect.navDrawer.NavDrawerItem;
import com.example.classconnect.navDrawer.NavDrawerListAdapter;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

public class MainActivity extends Activity {
        // Add New Class variables
        EditText className;
        Button startTime;
        Button endTime;
        EditText teacherName;
        CheckBox monday;
        CheckBox tuesday;
        CheckBox wednesday;
        CheckBox thursday;
        CheckBox friday;
        CheckBox saturday;
        
        ImageView imgFavorite;
        
        
        // Nav Drawer variables
        private DrawerLayout mDrawerLayout;
        private ListView mDrawerList;
        private ActionBarDrawerToggle mDrawerToggle;

        // nav drawer title
        private CharSequence mDrawerTitle;

        // used to store app title
        private CharSequence mTitle;

        // slide menu items
        private String[] navMenuTitles;
        private TypedArray navMenuIcons;

        private ArrayList<NavDrawerItem> navDrawerItems;
        private NavDrawerListAdapter adapter;
        private User currentUser;
        private String mEmail;
        private ArrayList<String> allUsers = new ArrayList<String>();
        
        //DB values
    	private MobileServiceClient mClient;
    	private MobileServiceTable<User> mUserTable;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                
                setContentView(R.layout.test_activity);
                try {
					mClient = new MobileServiceClient(
						      "https://classconnect.azure-mobile.net/",
						      "HzaUWkJBnWTXxCuREwxyQSaxJSyyJm51",
						      this
						);
					// TODO: 3 Get the Mobile Service Table instance to use
					mUserTable = mClient.getTable(User.class);
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        			currentUser = getIntent().getExtras().getParcelable("currentUser");
        		
        		
        		mUserTable.select("email").execute(new TableQueryCallback<User>(){

					@Override
					public void onCompleted(List<User> result, int arg1,
							Exception arg2, ServiceFilterResponse arg3) {
						// TODO Auto-generated method stub
						if(arg2 == null){
							for(User i : result){
								allUsers.add(i.getEmail());
							}
						} else{
							System.out.println("Error");
						}
					}
        			
        		});
        		
                
                imgFavorite = (ImageView) findViewById(R.id.imageView1);

                mTitle = mDrawerTitle = getTitle();

                // load slide menu items
                navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

                // nav drawer icons from resources
                navMenuIcons = getResources()
                                .obtainTypedArray(R.array.nav_drawer_icons);

                mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
                mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

                navDrawerItems = new ArrayList<NavDrawerItem>();

                // adding nav drawer items to array
                // Home
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
                
                // Edit Profile Picture
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
                
                // Edit Profile Information
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
                
                // Classes
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
                
                // Friends, can add a counter here like below (22)
                                //navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
                
                // School Map
                //navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
                
                // Log off
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
                
                // Recycle the typed array
                navMenuIcons.recycle();

                mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

                // setting the nav drawer list adapter
                adapter = new NavDrawerListAdapter(getApplicationContext(),
                                navDrawerItems);
                mDrawerList.setAdapter(adapter);

                // enabling action bar app icon and behaving it as toggle button
                getActionBar().setDisplayHomeAsUpEnabled(true);
                getActionBar().setHomeButtonEnabled(true);

                mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                                R.drawable.ic_drawer, //nav menu toggle icon
                                R.string.app_name, // nav drawer open - description for accessibility
                                R.string.app_name // nav drawer close - description for accessibility
                ) {
                        public void onDrawerClosed(View view) {
                                getActionBar().setTitle(mTitle);
                                // calling onPrepareOptionsMenu() to show action bar icons
                                invalidateOptionsMenu();
                        }

                        public void onDrawerOpened(View drawerView) {
                                getActionBar().setTitle(mDrawerTitle);
                                // calling onPrepareOptionsMenu() to hide action bar icons
                                invalidateOptionsMenu();
                        }
                };
                mDrawerLayout.setDrawerListener(mDrawerToggle);

                if (savedInstanceState == null) {
                        // on first time display view for first nav item
                        displayView(0);
                }
                
                
        }

        /**
         * Slide menu item click listener
         * */
        private class SlideMenuClickListener implements
                        ListView.OnItemClickListener {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
                        // display view for selected nav drawer item
                        displayView(position);
                }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
                // toggle nav drawer on selecting action bar app icon/title
                if (mDrawerToggle.onOptionsItemSelected(item)) {
                        return true;
                }
                // Handle action bar actions click
                switch (item.getItemId()) {
                case R.id.action_settings:
                	Intent shareIntent = new Intent(Intent.ACTION_SEND);
       			  shareIntent.setType("text/plain");
       			  shareIntent.putExtra(Intent.EXTRA_TEXT, "Come try out Class Connect, the hot new Android app to meet your friends in class!");
       			  startActivity(Intent.createChooser(shareIntent, "Share..."));
                        return true;
                default:
                        return super.onOptionsItemSelected(item);
                }
        }

        /* *
         * Called when invalidateOptionsMenu() is triggered
         */
        @Override
        public boolean onPrepareOptionsMenu(Menu menu) {
                // if nav drawer is opened, hide the action items
                boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
                menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
                return super.onPrepareOptionsMenu(menu);
        }

        /**
         * Diplaying fragment view for selected nav drawer list item
         * */
        private void displayView(int position) {
                // update the main content by replacing fragments
                Fragment fragment = null;
                switch (position) {
                case 0:
                        fragment = new HomeFragment();
                        break;
                case 1:
                        fragment = new ProfileFragment();
                        break;
                case 2:
                        fragment = new UpdateUserInfoFragment();
                    break;
                case 3:
                        fragment = new AddNewClassFragment();
                        break;
                case 4:
                        fragment = new FriendsFragment();
                    break;      
                case 5: 
                        fragment = new MapFragment();
                        break;
                case 6:
                	Toast.makeText( MainActivity.this,
            				"Logging Off!",
            				Toast.LENGTH_LONG).show();
            	    Intent myIntent = new Intent(MainActivity.this, LoginActivity.class);
            		// *** in the future we want to pass user credentials to next activity
            		startActivity(myIntent);
            		finish();
                        break;

                default:
                        break;
                }
                	
                if (fragment != null) {
                	Bundle B = new Bundle();
                	B.putParcelable("CURRENTUSER", currentUser);
                	if(position == 4){
                		B.putStringArrayList("ALLUSERS", allUsers);
                	}
                		fragment.setArguments(B);
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction()
                                        .replace(R.id.frame_container, fragment).commit();

                        // update selected item and title, then close the drawer
                        mDrawerList.setItemChecked(position, true);
                        mDrawerList.setSelection(position);
                        setTitle(navMenuTitles[position]);
                        mDrawerLayout.closeDrawer(mDrawerList);
                } else {
                	if(position != 6){
                        // error in creating fragment
                        Log.e("MainActivity", "Error in creating fragment");
                	}
                }
        }

        @Override
        public void setTitle(CharSequence title) {
                mTitle = title;
                getActionBar().setTitle(mTitle);
        }

        /**
         * When using the ActionBarDrawerToggle, you must call it during
         * onPostCreate() and onConfigurationChanged()...
         */

        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
                super.onPostCreate(savedInstanceState);
                // Sync the toggle state after onRestoreInstanceState has occurred.
                mDrawerToggle.syncState();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
                super.onConfigurationChanged(newConfig);
                // Pass any configuration change to the drawer toggls
                mDrawerToggle.onConfigurationChanged(newConfig);
        }
        
        
        // ****** ADD NEW CLASS FRAGMENT CODE *******
       /* public void startTimePickerDialog(View v) {
            DialogFragment newFragment = new StartTimePickerFragment();
            newFragment.show(getFragmentManager(), "startTime");
        }
        public void endTimePickerDialog(View v) {
            DialogFragment newFragment = new EndTimePickerFragment();
            newFragment.show(getFragmentManager(), "endPicker");

        }*/
        
        public void addNewClass(View V)
        {
                
                // Add New Class variable initialization
         /*       className = (EditText) findViewById(R.id.enterClass);
                startTime = (Button) findViewById(R.id.button2);
                endTime = (Button) findViewById(R.id.button3);
                teacherName = (EditText) findViewById(R.id.editText4);
                monday = (CheckBox) findViewById(R.id.checkBox1);
                tuesday = (CheckBox) findViewById(R.id.checkBox2);
                wednesday = (CheckBox) findViewById(R.id.checkBox3);
                thursday = (CheckBox) findViewById(R.id.checkBox4);
                friday = (CheckBox) findViewById(R.id.checkBox5);
                saturday = (CheckBox) findViewById(R.id.checkBox6);   */  
                
                // get the Entered  message
                String item1 = className.getText().toString();
                String item2 = teacherName.getText().toString();
                item1 = new StringBuilder().append(item1).append(" with ").append(item2).toString();
                String ST = startTime.getText().toString();
                if (ST.equals("Start Time")){
                        Toast.makeText(this, "PLEASE ENTER START TIME",   Toast.LENGTH_SHORT).show();
                        return;
                }
                String ET = endTime.getText().toString();
                if (ET.equals("End Time")){
                        Toast.makeText(this, "PLEASE ENTER END TIME",   Toast.LENGTH_SHORT).show();
                        return;
                }
                //Format Time
                int SHour = ST.codePointBefore(2);
                int SMin  = ST.codePointCount(3, 5);
                int EHour = ET.codePointBefore(2);
                int EMin  = ET.codePointCount(3, 5);
                Calendar beginTime = Calendar.getInstance();
                beginTime.set(2014, 3, 8, SHour, SMin);
                Calendar ENDTIME = Calendar.getInstance();
                ENDTIME.set(2014, 3, 8, EHour, EMin);
                Intent intentCalendar = new Intent(Intent.ACTION_INSERT);
                intentCalendar.setType("vnd.android.cursor.item/event");
                //set title
                intentCalendar.putExtra(Events.TITLE, item1);
                
                
                // Debugging toast
                Toast.makeText( MainActivity.this,
                                                "Add new class: " + item1,
                                                Toast.LENGTH_LONG).show();
                String dates = "BYDAY=";
                boolean first = true;
                // Check box
                                if(monday.isChecked()){
                                        if(first){
                                        dates = new StringBuilder().append(dates).append("MO").toString();
                                        first = false;
                                        } else{
                                                dates = new StringBuilder().append(dates).append(",MO").toString();
                                        }
                                }
                                if(tuesday.isChecked())

                                        if(first){
                                        dates = new StringBuilder().append(dates).append("TU").toString();
                                        first = false;
                                        } else{
                                                dates = new StringBuilder().append(dates).append(",TU").toString();
                                        }
                                
                                if(wednesday.isChecked())

                                        if(first){
                                        dates = new StringBuilder().append(dates).append("WE").toString();
                                        first = false;
                                        } else{
                                                dates = new StringBuilder().append(dates).append(",WE").toString();
                                        }
                                
                                if(thursday.isChecked())

                                        if(first){
                                        dates = new StringBuilder().append(dates).append("TH").toString();
                                        first = false;
                                        } else{
                                                dates = new StringBuilder().append(dates).append(",TH").toString();
                                        }
                                
                                if(friday.isChecked())

                                        if(first){
                                        dates = new StringBuilder().append(dates).append("FR").toString();
                                        first = false;
                                        } else{
                                                dates = new StringBuilder().append(dates).append(",FR").toString();
                                        }
                                
                                if(saturday.isChecked())

                                        if(first){
                                        dates = new StringBuilder().append(dates).append("SA").toString();
                                        first = false;
                                        } else{
                                                dates = new StringBuilder().append(dates).append(",SA").toString();
                                        }
                                //add time
                                intentCalendar.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis());
                                intentCalendar.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, ENDTIME.getTimeInMillis());
                                //add recurring event information
                                intentCalendar.putExtra(Events.RRULE, dates);
                                
                                // put the message in Intent
                                intentCalendar.putExtra("CLASS", item1);

                                setResult(2,intentCalendar);
                        
                        //finish();
        }
        
        
        // *** UPDATE USER INFO FRAGMENT CODE
        public void updateUserInfo(View V)
        {
                // get the Entered  message
//              String item1 = info.getText().toString();
//              String item2 = hobbies.getText().toString();
//              String item3 = hobbies.getText().toString();
//              String item4 = hobbies.getText().toString();
                
                // temporary notification
                // notify the user that their info was updated
                String info = "Profile information updated.";
                Toast.makeText(getApplicationContext(), info , Toast.LENGTH_SHORT).show();
                        
        }
        
        
        // profile picture handler
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);          
        }
        
        public User getCurrentUser(){
        	return currentUser;
        	
        }

}